﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NewsMine.DomainObjects;
using System.Text.RegularExpressions;
using System.IO;

namespace NewsDiscoveryEngine.Cleansing
{
    /// <summary>
    /// Some times image urls are not coming properly, so we need to fix them or remove them completely.
    /// </summary>
    public class ImageCleanser:ICleanser
    {
        public List<HtmlLink> Cleanse(List<HtmlLink> htmlLinks)
        {
            List<HtmlLink> resultedHtmlLinks = new List<HtmlLink>();
            foreach (HtmlLink link in htmlLinks)
            {
                if (IsValidHtmlLink(link) == true)
                {
                    resultedHtmlLinks.Add(link);
                }
                else
                {
                    //todo: think of adding the domain image as a default image.
                    link.ImageUrl = string.Empty;

                    resultedHtmlLinks.Add(link);
                }
            }

            return resultedHtmlLinks;
        }


        public bool IsValidHtmlLink(HtmlLink htmlLink)
        {

            if (string.IsNullOrEmpty(htmlLink.ImageUrl))
                return false;
            //see if the url is having proper file name.

            Uri uri = new Uri(htmlLink.ImageUrl);
            string filename = System.IO.Path.GetFileName(uri.LocalPath);
            if (string.IsNullOrEmpty(filename))
                return false;

            //see if the url is in the list of noImage urls.

            string[] invalidImageUrls = GetInvalidImageUrlsToBeRemoved();

            foreach (var invalidImageUrl in invalidImageUrls)
            {
                if (!string.IsNullOrEmpty(htmlLink.ImageUrl) && htmlLink.ImageUrl.ToLower() == invalidImageUrl.ToLower())
                {
                    return false;
                }
                else
                {

                  
                    continue;
                    
                }
            }

            return true;
        }

        private string[] GetInvalidImageUrlsToBeRemoved()
        {
            //todo: These patterns can be read from the file; 
            return new string[] { "http://tamil.oneindia.in/images/noimage.jpg" };
        }
    }
}
